
using System;
using System.Collections.Generic;
using System.Linq;
using MonoMac.Foundation;
using MonoMac.AppKit;
using System.Drawing;
using MonoMac.CoreGraphics;

namespace SpyTouchClient
{
	[Register("ScreenView")]
	public partial class ScreenView : MonoMac.AppKit.NSView
	{
		#region Constructors

		// Called when created from unmanaged code
		public ScreenView (IntPtr handle) : base(handle)
		{
			Initialize ();
		}

		// Called when created directly from a XIB file
		[Export("initWithCoder:")]
		public ScreenView (NSCoder coder) : base(coder)
		{
			Initialize ();
		}

		// Shared initialization code
		void Initialize ()
		{
		}

		#endregion

		NSColor _backColor = NSColor.TextBackground;
		NSColor _lineColor = NSColor.Text;
		NSColor _selColor = NSColor.SelectedControl;

		Dictionary<long, List<ViewBasicInfo>> _subviews = new Dictionary<long, List<ViewBasicInfo>> ();

		long _selectedViewHandle;
		public long SelectedViewHandle {
			get { return _selectedViewHandle; }
			set {
				_selectedViewHandle = value;
				SetNeedsDisplayInRect (Bounds);
			}
		}

		public Dictionary<long, List<ViewBasicInfo>> Data {
			get { return _subviews; }
			set {
				_subviews = value;
				SetNeedsDisplayInRect (Bounds);
			}
		}

		NSColor _fillColor = NSColor.FromCalibratedRGBA (0.6f, 0.6f, 0.6f, 0.1f);
		NSColor _selFillColor = NSColor.SelectedControl;

		public override void DrawRect (RectangleF dirtyRect)
		{
			var nsc = NSGraphicsContext.CurrentContext;
			nsc.ShouldAntialias = true;
			var c = nsc.GraphicsPort;

			c.TranslateCTM (0, Frame.Height);
			c.ScaleCTM (1, -1);

			_backColor.Set ();
			NSGraphics.RectFill (Bounds);

			if (!Data.ContainsKey (0))
				return;
			_lineColor.Set ();
			var width = 10.0f;
			var height = 10.0f;
			foreach (var o in Data[0]) {
				width = Math.Max (width, o.Frame.Width);
				height = Math.Max (height, o.Frame.Height);
			}

			var viewSize = Bounds.Size;

			var margin = 10;

			var scale = 1.0f;

			var vw = viewSize.Width - 2 * margin;
			var vh = viewSize.Height - 2 * margin;

			if (vw < 1 || vh < 1) return;

			if (width > vw) {
				scale = vw / width;
				width *= scale;
				height *= scale;
			}
			if (height > vh) {
				var a = vh / height;
				scale *= a;
				width *= a;
				height *= a;
			}

			c.TranslateCTM (margin, margin);
			c.ScaleCTM (scale, scale);

			c.SetLineWidth(1.0f);

			foreach (var o in Data[0]) {
				Draw (c, o, 0, 0);
			}
		}

		void Draw (CGContext c, ViewBasicInfo v, float x, float y)
		{
			var r = v.Frame;
			r.Offset (x, y);
			c.AddRect (r);

			if (v.ViewHandle == SelectedViewHandle) {
				_selFillColor.SetFill ();
			} else {
				_fillColor.SetFill ();
			}

			c.DrawPath (CGPathDrawingMode.FillStroke);

			if (Data.ContainsKey (v.ViewHandle)) {
				foreach (var s in Data[v.ViewHandle]) {
					Draw (c, s, x + v.Frame.Left, y + v.Frame.Top);
				}
			}
		}

	}
}

